<?php

namespace App\Http\Middleware;

use Closure;
use Exception;
use Illuminate\Http\Request;

class VerifyToken
{
    /**
     * Handle an incoming request.
     *
     * @param Request $request
     * @param Closure $next
     * @return mixed
     * @throws Exception
     */
    public function handle(Request $request, Closure $next): mixed
    {
        $tokenPrefix = l('base.tokenPrefix');
        $token = request()->header(str_replace(':', '', $tokenPrefix));
        if (is_null($token) || !is_string($token) || strlen($token) != 32) return fail(430);
        else if (!cache()->has($tokenPrefix . $token)) return fail(430);
        define('TOKEN', $token);
        define('USERID', cache($tokenPrefix . $token));
        return $next($request);
    }
}
